package com.block.datapush.form.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.item.util.HappyUtil;
import com.block.datapush.form.item.util.ZiWeiHuaUtil;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 紫薇花API
 */
@Service
public class ZiWeiHuaHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

        String queryUrl = formInfo.getQueryUrl();
        String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

        Map<String, Object> bizParamMap = new HashMap<>();
        bizParamMap.put("userPhone", mobileMd5);

        log.info("【紫薇花】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
//                    .body(JSON.toJSONString(bizParamMap))
                .form(bizParamMap)
                .execute().body();
        log.info("【紫薇花】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        if (ObjectUtil.equal(code, Integer.valueOf(1))) {
            return true;
        }
        return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

        String queryUrl = formInfo.getRequestUrl();
        Map<String, Object> bizParamMap = new HashMap<>();
        bizParamMap.put("phone",memberExtInfo.getMobile());
        bizParamMap.put("id_card",memberExtInfo.getIdCard());
        bizParamMap.put("real_name",memberExtInfo.getUsername());
        bizParamMap.put("source","BBD");
        bizParamMap.put("sesame_points", ZiWeiHuaUtil.getZhima(memberExtInfo.getZhimaScore()));
        bizParamMap.put("credit_card",21);
        bizParamMap.put("house",ZiWeiHuaUtil.getHouse(memberExtInfo.getHouse()));
        bizParamMap.put("car",ZiWeiHuaUtil.getCar(memberExtInfo.getCar()));
        bizParamMap.put("fund",ZiWeiHuaUtil.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("social",ZiWeiHuaUtil.getShebao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("jd_ious",ZiWeiHuaUtil.getbaitiao(memberExtInfo.getBaitiao()));
        bizParamMap.put("equipment","AndroidOS");
        bizParamMap.put("agent_id",formInfo.getApiCode());
        bizParamMap.put("city",memberExtInfo.getCity());
        bizParamMap.put("ip",memberExtInfo.getReqIp());

        String jsonParamMap = JSON.toJSONString(bizParamMap);
        String key =formInfo.getApiKey();
        String iv =formInfo.getApiSecret();
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
        String reqData = aes.encryptBase64(jsonParamMap);

        Long timestamp = System.currentTimeMillis();
        String version = "1.0.0";

        String finalParamString = StrUtil.format("version={}&reqData={}&timestamp={}", version, reqData, timestamp);

        // 进行MD5签名
        String sign = SecureUtil.md5(finalParamString);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("version", version);
        paramMap.put("reqData",reqData);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);


        log.info("【紫薇花】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                //.header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .form(paramMap)
                .execute().body();
        log.info("【紫薇花】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushResultDTO.setResult(result);
        pushResultDTO.setCode(String.valueOf(code));
        pushResultDTO.setMessage(msg);
        pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));
        if (ObjectUtil.equal(code, Integer.valueOf(1))) {
            pushResultDTO.setSuccess(true);
            pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
        } else {
            pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
            pushResultDTO.setSuccess(false);
        }
        return pushResultDTO;
    }




    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
